// pages/mine/mine.js

const TimeUtils = require('../../utils/timeUtils')
const lunarCalendar = require('../../utils/calendar')
import request from "../../utils/request.js";
import auth from "../../utils/auth.js";
import local from "../../utils/local";
import nav from "../../utils/nav.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    appid: 'wx15a7538fa77ddfc0',
    date_day: '',
    date_month: '',
    date_year: '',
    date_time: '',
    date_noli: '',
    date_week: '',

    headerYear: '',
    headerMonth: '',
    headerDay: '',
    headerHour: '',

    middleYear: '',
    middleMonth: '',
    middleDay: '',
    middleHour: '',

    headerYearColor: '',
    headerMonthColor: '',
    headerDayColor: '',
    headerHourColor: '',

    middleYearColor: '',
    middleMonthColor: '',
    middleDayColor: '',
    middleHourColor: '',

    itemList: [
      // {'url': '/images/tabbar/mine.png', 'name': '生日解析', 'id': 0},
      // {'url': '/images/tabbar/mine.png', 'name': '起名工具', 'id': 1},
      // {'url': '/images/tabbar/mine.png', 'name': '姓名解析', 'id': 2},
      {'url': '/images/tabbar/mine.png', 'name': '起名工具', 'id': 0},
    ],
    privacyVisible: false,
   
    memberID: '',

    greenColor: '#007700',
    redColor: '#FF0000',
    brownColor: '#972100',
    yellowColor: '#FFC600',
    blackColor: '#131313',


  },

  onClickToDetail(e) {
    // if (this.data.memberID == '' || this.data.memberID == '0') {
    //   nav.navigateTo('/login/login')
    // }else {
      const id = e.currentTarget.id;
      let tempDic = {}
      for (let i = 0; i < this.data.itemList.length; i ++) {
        const dic = this.data.itemList[i]
        if (dic.id == id) {
          tempDic = {
            id: id,
            title: dic.name,
          }
        }
      }
      let jsonStr = JSON.stringify(tempDic)
      let data = encodeURIComponent(jsonStr)
      nav.navigateTo('/analysis/analysis?data='+data)
    // }
    
  },

  macthColor(key) {
    if (key == '甲' || key == '乙' || key == '寅' || key == '卯') {
      return '#007700'
    }
    if (key == '丙' || key == '丁' || key == '巳' || key == '午') {
      return '#FF0000'
    }
    if (key == '戊' || key == '己' || key == '辰' || key == '戌' || key == '丑' || key == '未') {
      return '#972100'
    }
    if (key == '庚' || key == '辛' || key == '申' || key == '酉') {
      return '#FFC600'
    }
    if (key == '壬' || key == '癸' || key == '亥' || key == '子') {
      return '#131313'
    }
  },

  // /notlogindataserv?param={“eventCode”:1}
  getNotlogindataserv() {
    const that = this;
    let dic = {
      "appId": this.data.appid,
      "eventCode": "1"
    }
    let url = '/notlogindataserv'
    request.get(url,{param: dic}).then((res) => {
      const returnCode = res.RETURN
      if (returnCode == 1) {
        const baZhi_string = res.baZhi_string
        var baZhiObject = JSON.parse(baZhi_string)
        const result = baZhiObject.result
        console.log(result)
        const eight = result.eightAll.eight
        console.log(eight)
        const headerYear = eight[0].substring(0, 1);
        const headerYearColor = that.macthColor(headerYear);
        const middleYear = eight[0].substring(1, 2);
        const middleYearColor = that.macthColor(middleYear);
        const headerMonth = eight[1].substring(0, 1);
        const headerMonthColor = that.macthColor(headerMonth);
        const middleMonth = eight[1].substring(1, 2);
        const middleMonthColor = that.macthColor(middleMonth);
        const headerDay = eight[2].substring(0, 1);
        const headerDayColor = that.macthColor(headerDay);
        const middleDay = eight[2].substring(1, 2);
        const middleDayColor = that.macthColor(middleDay);
        const headerHour = eight[3].substring(0, 1);
        const headerHourColor = that.macthColor(headerHour);
        const middleHour = eight[3].substring(1, 2);
        const middleHourColor = that.macthColor(middleHour);
        that.setData({
          date_year: result.year,
          date_month: result.month,
          date_day: result.day,
          date_week: result.ncWeek,
          date_noli: '农历' + result.ImonthCn + result.IDayCn,

          headerYear: headerYear,
          headerMonth: headerMonth,
          headerDay: headerDay,
          headerHour: headerHour,

          middleYear: middleYear,
          middleMonth: middleMonth,
          middleDay: middleDay,
          middleHour: middleHour,

          headerYearColor: headerYearColor,
          headerMonthColor: headerMonthColor,
          headerDayColor: headerDayColor,
          headerHourColor: headerHourColor,

          middleYearColor: middleYearColor,
          middleMonthColor: middleMonthColor,
          middleDayColor: middleDayColor,
          middleHourColor: middleHourColor,
          
        });

      }
    })
  },



  onClickToAgree(e) {
    local.setLocal('showPrivacy', 'true')
    wx.showTabBar({
      animation: false,
      success:(res) => {
        this.setData({
          privacyVisible: false,
        })
      },
      fail: function(err) {
      }
    })
  },

  onClickToProtocl(e) {
    const id = e.currentTarget.id;
    let tempDic = {}
    if (id == 'user') {
      tempDic = {
        url: 'http://www.opencc.cn/xsj_serv.html',
        title: '用户服务协议'
      }
    }else if (id == 'privacy') {
      tempDic = {
        url: 'http://www.opencc.cn/xsj_priv.html',
        title: '隐私保护政策'
      }
    }
    let jsonStr = JSON.stringify(tempDic)
    let data = encodeURIComponent(jsonStr)
    nav.navigateTo('/webview/webview?data='+data)
  },



  onClickToDisagree(e) {
    wx.exitMiniProgram({
      success: (res) => {
        
      }
    })
    // wx.showTabBar({
    //   animation: false,
    //   success:(res) => {
    //     wx.exitMiniProgram({
    //       success: (res) => {

    //       }
    //     })
    //   },
    //   fail: function(err) {
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // const str = 'prepay_id=wx2221420200886292a0d6c55e1efaf20001'
    // let arr = str.split('prepay_id=')
    // console.log(arr)
    const showPrivacy = local.getLocal('showPrivacy');
    
    if (showPrivacy != 'true') {
      wx.hideTabBar({
        animation: false,
        success:(res) => {
          this.setData({
            privacyVisible: true,
          })
        },
        fail: function(err) {
        }
      });
    }

    // const solar2lunarObj = lunarCalendar.solar2lunar();
    // const year = solar2lunarObj.cYear;
    // const month = solar2lunarObj.cMonth;
    // const day = solar2lunarObj.cDay;
    // const week = solar2lunarObj.ncWeek;
 
    // const headerYear = solar2lunarObj.gzYear.substring(0, 1);
    // const middleYear = solar2lunarObj.gzYear.substring(1, 2);
    // const headerMonth = solar2lunarObj.gzMonth.substring(0, 1);
    // const middleMonth = solar2lunarObj.gzMonth.substring(1, 2);
    // const headerDay = solar2lunarObj.gzDay.substring(0, 1);
    // const middleDay = solar2lunarObj.gzDay.substring(1, 2);
    // const headerHour = solar2lunarObj.gzHour.substring(0, 1);
    // const middleHour = solar2lunarObj.gzHour.substring(1, 2);
    // this.setData({
    //   date_year: year,
    //   date_month: month,
    //   date_day: day,
    //   date_week: week,
    //   date_noli: '农历' + solar2lunarObj.IMonthCn + solar2lunarObj.IDayCn,

    //   headerYear: headerYear,
    //   headerMonth: headerMonth,
    //   headerDay: headerDay,
    //   headerHour: headerHour,

    //   middleYear: middleYear,
    //   middleMonth: middleMonth,
    //   middleDay: middleDay,
    //   middleHour: middleHour,
    // });
    
    this.getNotlogindataserv()

    this.getPaipanmemberservice2()

  },

  getPaipanmemberservice2() {
    const that = this;
    let dic = {}
    const url = '/paipanmemberservice?appId='+ this.data.appid +'&eventCode=2'
    request.get(url,dic).then((res) => {
      console.log(res)
      const returnCode = res.RETURN
      if (returnCode == 1) {
        const object = res.APP_DB_INFO
        that.setData({
          jndiName: object.jndiName,
          secret: object.SECRET,
        })
        local.setLocal("jndiName", object.jndiName);
        that.getLoginCode()
      }
    })
  },

  getLoginCode() {
    var that = this
    wx.login({
      success: (res) => {
        console.log(res)
        const code = res.code
        that.setData({
          js_code: code
        })
        that.getOpenId(code)
      },
    })
  },

  getOpenId(code) {
    const that = this
    let dic = {
      'appId': this.data.appid,
      'js_code': code,
      'jndiName': this.data.jndiName,
      'grant_type': 'authorization_code',
      'eventCode': '111',
    }
    console.log(dic)
    let url = '/paipanmemberservice?appId='+ this.data.appid +'&js_code=' + code +'&jndiName=' + this.data.jndiName +'&grant_type=authorization_code&eventCode=111'
    request.get(url, {}).then((res) => {
      console.log(res)
      const returnCode = res.return
      if (returnCode == 1) {
        const tempOpenId = res.openid
        const tempSessionKey = res.session_key
        that.setData({
          openId: tempOpenId,
          session_key: tempSessionKey
        })
        if (tempOpenId.length != 0) {
          local.setLocal("openId", tempOpenId);
          that.getPaipanmemberservice1()
        }else{
          toast.showToast('获得信息异常，请重新进入小程序。')
        }
        
      }
    })
    
  },

  getPaipanmemberservice1() {
    console.log("getPaipanmemberservice1")
    const that = this;
    let dic = {}
    const url = '/paipanmemberservice?appId='+ this.data.appid + '&openId=' + this.data.openId +'&eventCode=1'
    request.get(url,dic).then((res) => {
      console.log(res)
      const returnCode = res.RETURN
      if (returnCode == 1) {
        const memInfo = res.MEM_INFO
        const memberID = memInfo.memberID
        const tel = memInfo.tel
        const memberName = memInfo.memberName
        if (memberID == 0) {
          that.getWxloginservlet()
        }else {
          console.log("==========================")
          local.setLocal("memberID", memberID);
          local.setLocal("tel", tel);
          local.setLocal("memberName", memberName);
        }
      }
    })
  },

  getWxloginservlet() {
    const that = this;
    let dic = {
      appid: this.data.appid,
      secret: '',
      encrypdata: '',
      ivdata: '',
      sessionkey: this.data.session_key,
      jndiName: this.data.jndiName,
      eventCode: '16',
      nickName: '微信用户',
      gender: '0',
      avatarUrl: '',
      country: '',
      province: '',
      city: '',
      openId: this.data.openId,
      parentOpenId: '0'
    };
    console.log(dic)
    request.get("/wxloginservlet", dic).then(res => {
      console.log(res)
      const returnCode = res.RETURN
      if (returnCode == 1) {
        that.getPaipanmemberservice1()
      }
    });
  },

  handleImageBtnTap() {

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const memberID = local.getLocal('memberID');
    this.setData({
      memberID: memberID
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})


// // index.js
// const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

// Page({
//   data: {
//     motto: 'Hello World',
//     userInfo: {
//       avatarUrl: defaultAvatarUrl,
//       nickName: '',
//     },
//     hasUserInfo: false,
//     canIUseGetUserProfile: wx.canIUse('getUserProfile'),
//     canIUseNicknameComp: wx.canIUse('input.type.nickname'),
//   },
//   bindViewTap() {
//     wx.navigateTo({
//       url: '../logs/logs'
//     })
//   },
//   onChooseAvatar(e) {
//     const { avatarUrl } = e.detail
//     const { nickName } = this.data.userInfo
//     this.setData({
//       "userInfo.avatarUrl": avatarUrl,
//       hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
//     })
//   },
//   onInputChange(e) {
//     const nickName = e.detail.value
//     const { avatarUrl } = this.data.userInfo
//     this.setData({
//       "userInfo.nickName": nickName,
//       hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
//     })
//   },
//   getUserProfile(e) {
//     // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
//     wx.getUserProfile({
//       desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
//       success: (res) => {
//         console.log(res)
//         this.setData({
//           userInfo: res.userInfo,
//           hasUserInfo: true
//         })
//       }
//     })
//   },
// })
